/******************** ��ʢ���ӹ����� ********************
 * �ļ���  ��main.c
 * ����    ������ͬ����MINI�����ش˳���󣬰���һ�������ϵİ��������Ե�����һ������
 *           �϶�Ӧ��LED���������Ӳ������ӡ�         
 * ʵ��ƽ̨��MINI STM32������ ����STM32F103C8T6
 * ��汾  ��ST3.0.0   																										  
 * �Ա��꣺http://shop66177872.taobao.com
*********************************************************/
#include "stm32f10x.h"
#include "can.h"
#include "led.h"
#include "adc.h"
#include "relay.h"
#include "delay.h"
#include "usart.h"
#include "rs485.h"
#include "common.h"
#include <stdbool.h>
#include "liquid_cooling_controller.h"

#define RADIATION_ENABLE 0
#define RADIATION_DISABLE 1

__IO u32 can_recv_flag = 0x00;  //���ڱ�־�Ƿ���յ����ݣ����жϺ����и�ֵ
CanTxMsg TxMessage;         //���ͻ�����
CanRxMsg RxMessage;         //���ջ�����

static u8 can_tx_buf[20] = {0};
static u16 can_temp_buf[18] = {0}; // 记录1-18号温度传感器的温度数据
static u16 can_temp_max = 0; // 1-18号温度传感器的最大温度数据
static u16 can_temp_gun1 = 0; // 液冷枪1温度数据
static u16 can_temp_gun2 = 0; // 液冷枪2温度数据
static u16 can_charge_status = 0; // 充电状态
static bool hasGetCanTempGunData = false; // 是否读取到液冷枪温度数据

static u8 rs485_tx_buf[20] = {0};
static u8 rs485_rx_buf[20] = {0};
static u16 rs485_rx_cnt = 0;  // 记录接收到的485数据个数
static float rs485_temp_data1 = 0;  // 连接到485总线上的温度传感器1的数据
static float rs485_temp_data2 = 0;  // 连接到485总线上的温度传感器2的数据
static bool hasGetRS485TempData = false; // 是否读取连接到485总线上的温度传感器的数据

static float ntc_temp_data = 0; // 热敏电阻的温度数据
static bool hasGetNtcTempData = false; // 是否读取到热敏电阻的温度数据

static u8 uart1_rx_buf[20] = {0};
static u16 uart1_rx_cnt = 0;  // 记录uart1接收到的数据个数
// static char threshold[15] = {0}; // 记录阈值的数组
static char THRESHOLD_X1 = 0; // X1阈值
static char THRESHOLD_X2 = 0; // X2阈值
static char THRESHOLD_X3 = 0; // X3阈值
static char THRESHOLD_X4 = 0; // X4阈值

static char THRESHOLD_Y1 = 30; // Y1阈值
static char THRESHOLD_Y2 = 0; // Y2阈值
static char THRESHOLD_Y3 = 0; // Y3阈值
static char THRESHOLD_Y4 = 0; // Y4阈值

static char THRESHOLD_Z1 = 0; // Z1阈值
static char THRESHOLD_Z2 = 0; // Z2阈值
static char THRESHOLD_Z3 = 0; // Z3阈值
static char THRESHOLD_Z4 = 0; // Z4阈值

static char THRESHOLD_W1 = 0; // W1阈值
static char THRESHOLD_W2 = 0; // W2阈值
static char THRESHOLD_W3 = 0; // W3阈值
// static char THRESHOLD_W4 = 0; // W4阈值

/*�����ܽų�ʼ��*/
void KeyInit(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOC  , ENABLE  );  
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4|GPIO_Pin_5 ;		//C4 C5Ϊ�ⲿ���� ��Ϊ2�������ⲿ���밴��	
  GPIO_InitStructure.GPIO_Mode =  GPIO_Mode_IPU ;		   // ����	
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;		 // �����������50MHz
  GPIO_Init(GPIOC, &GPIO_InitStructure);				 // ѡ��C�˿�
}

/*����Ƿ��а�������*/
void  GetKey(void)
{
  if(Bit_RESET == GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4))
  {
    delay_ms(100); //ȥ����//ȥ����
    if(Bit_RESET == GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4))
    {
      while(Bit_RESET == GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4)){ ; }//�ȴ������ͷ�

    }
  }

  if(Bit_RESET == GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_5))
  {
    delay_ms(100); //ȥ����//ȥ����
    if(Bit_RESET == GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_5))
    {
      while(Bit_RESET == GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_5)){ ; }//�ȴ������ͷ�
    }
  }           
}

void CAN_Message_Process(CanRxMsg RxMessage) {
  u8 i = 0;
  // if(RxMessage.StdId != CAN_STDID) {
  //   USART1_printf(USART1, "\r\n Wrong RxMessage.StdId: %d\r\n", RxMessage.StdId);
  //   return;
  // } else {
    switch(RxMessage.ExtId) {
      case LCC_VersionInfo:
        USART1_printf(USART1, "\r\n RxMessage.ExtId is LCC_VersionInfo!\r\n");
        // can_temp_max = maxElement(can_temp_buf, 18);  // 获取1-18号温度传感器的最大温度数据
        // USART1_printf(USART1, "\r\n can_temp_max: %d\r\n", can_temp_max);
      break;
      case LCC_StatusInfo:
        USART1_printf(USART1, "\r\n RxMessage.ExtId is LCC_StatusInfo!\r\n");
        can_temp_gun1 = RxMessage.Data[5];  // 供液温度
        can_temp_gun2 = RxMessage.Data[4];  // 回液温度
        can_charge_status = RxMessage.Data[7];  // 充电状态
        hasGetCanTempGunData = true; // 顺利读取到液冷枪温度数据

        // 当最大值≥Y4，DO5控制散热3启动；
        if(can_temp_gun1 >= THRESHOLD_Y4 || can_temp_gun2 >= THRESHOLD_Y4) {
          RELAY_3(RADIATION_ENABLE);
        } else {
        }

        // 当最大值≥Z4，DO6控制散热4启动；
        if(can_temp_gun1 >= THRESHOLD_Z4 || can_temp_gun2 >= THRESHOLD_Z4) {
          RELAY_4(RADIATION_ENABLE);
        } else {
        }

        // 当最小值≦X4, DO3控制散热1启动；
        if(can_temp_gun1 <= THRESHOLD_X4 || can_temp_gun2 <= THRESHOLD_X4) {
          RELAY_1(RADIATION_ENABLE);
        } else {
        }
        // USART1_printf(USART1, "\r\n can_temp_gun1 is：%d\r\n", can_temp_gun1);
        // USART1_printf(USART1, "\r\n can_temp_gun2 is：%d\r\n", can_temp_gun2);
      break;
      case LCC_FaultInfo:
        USART1_printf(USART1, "\r\n RxMessage.ExtId is LCC_FaultInfo!\r\n");
      break;
      default:
      break;
    }
  // }
}

/* USB�жϺ�CAN�����жϷ������USB��CAN����I/O������ֻ�õ�CAN���жϡ� */
void USB_LP_CAN1_RX0_IRQHandler(void)
{
  CanRxMsg RxMessage;
  u8 i = 0;

  // RxMessage.StdId = CAN_STDID;
  // RxMessage.ExtId = CAN_EXTID;
  // RxMessage.IDE=0;
  // RxMessage.DLC=0;
  // RxMessage.FMI=0; 
  CAN_Receive(CAN1, CAN_FIFO0, &RxMessage); //����FIFO0�е�����
  CAN_Message_Process(RxMessage);

  // USART1_printf(USART1, "\r\n RECEIVE can data: %d \r\n", RxMessage.DLC);
}

void readRS485Temperature() {
  u8 i=0;
  rs485_tx_buf[0] = 0x00; // 设备地址，传00代表广播
  rs485_tx_buf[1] = 0x03; // 读指令
  rs485_tx_buf[2] = 0x00;
  rs485_tx_buf[3] = 0x00;
  rs485_tx_buf[4] = 0x00;
  rs485_tx_buf[5] = 0x01;
  rs485_tx_buf[6] = 0x85;
  rs485_tx_buf[7] = 0xDB;
  for(i=0; i<8; i++) {
    RS485_1_SendByte(rs485_tx_buf[i]);
  }
}

void getNTCTemperature() {
  ntc_temp_data = calculate_temperature(); // 获取板子上热敏电阻的数据
  hasGetNtcTempData = true; // 顺利读取到热敏电阻的温度数据
}

void processTemperatureData() {
  if (CRC16(rs485_rx_buf, rs485_rx_cnt)!=0) {
    USART1_printf(USART1, "\r\n CRC error!\r\n");
    return;
  } else {
    switch(rs485_rx_buf[1]) {
      // 功能代码03
      case 3:
        // 判断收到的设备的地址
        if(rs485_rx_buf[0] == 1) {
          rs485_temp_data1 = (float)(rs485_rx_buf[3]*256+rs485_rx_buf[4])/10;
          // 当温度≤X1，DO3控制散热1停止，DO4控制散热2停止；
          if(rs485_temp_data1 <= THRESHOLD_X1) {
            RELAY_1(RADIATION_DISABLE);
            RELAY_2(RADIATION_DISABLE);
          } else {
          }
          // 当温度≥Y1，DO5控制散热3启动；
          if(rs485_temp_data1 >= THRESHOLD_Y1) {
            USART1_printf(USART1, "\r\n rs485_temp_data1 >= THRESHOLD_Y1 \r\n");
            RELAY_3(RADIATION_ENABLE);
          } else {
          }
          // 当温度≥Z1，DO6控制散热4启动；
          if(rs485_temp_data1 >= THRESHOLD_Z1) {
            RELAY_4(RADIATION_ENABLE);
          } else {
          }
          // 当温度≤W1，DO5控制散热3停止，DO6控制散热4停止
          if(rs485_temp_data1 <= THRESHOLD_W1) {
            RELAY_3(RADIATION_DISABLE);
            RELAY_4(RADIATION_DISABLE);
          } else {
          }
        } else if(rs485_rx_buf[0] == 2) {
          rs485_temp_data2 = (float)(rs485_rx_buf[3]*256+rs485_rx_buf[4])/10;
          // 当温度≥X2，DO5控制散热3启动；
          if(rs485_temp_data2 >= THRESHOLD_X2) {
            RELAY_3(RADIATION_ENABLE);
          } else {
          }
          // 当温度≦Y2，DO6控制散热4启动；
          if(rs485_temp_data2 <= THRESHOLD_Y2) {
            RELAY_4(RADIATION_ENABLE);
          } else {
          }
          // 当温度≦Z2，DO3控制散热1启动；
          if(rs485_temp_data2 <= THRESHOLD_Z2) {
            RELAY_1(RADIATION_ENABLE);
          } else {
          }
          // 当温度≦W2，DO5控制散热3停止，DO6控制散热4停止
          if(rs485_temp_data2 <= THRESHOLD_W2) {
            RELAY_3(RADIATION_DISABLE);
            RELAY_4(RADIATION_DISABLE);
          } else {
          }
        }
        hasGetRS485TempData = true; // 顺利读取连接到485总线上的温度传感器的数据
        USART1_printf(USART1, "\r\n Temperature is:%d \r\n", rs485_rx_buf[3]*256+rs485_rx_buf[4]);
      break;
    }
  }
  rs485_rx_cnt = 0;
}

//�����жϴ���
void USART1_IRQHandler(void)
{
    u8 i = 0;
    if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
    {
        if(uart1_rx_cnt < sizeof(uart1_rx_buf)-1)
        {   //δ��������rs485_rx_buf��������򽫽��յ������ݱ��浽����rs485_rx_buf
            uart1_rx_buf[rs485_rx_cnt++] = USART_ReceiveData(USART2);
        }
        // ���USART2�Ľ����жϱ�־��USART_FLAG_RXNE�����Ա��ܹ�������һ���ֽڵ�����
        USART_ClearFlag(USART1, USART_FLAG_RXNE);
    }
    if(USART_GetITStatus(USART1, USART_IT_IDLE ) != RESET )//空闲中断 接收到一帧数据 产生一次中断
    {
        i = USART1->SR;	 //读取SR寄存器
        i = USART1->DR;    //读取DR寄存器 (先读USART_SR，然后读USART_DR可以清除空闲中断标志位IDLE)
        USART1_printf(USART1, "\r\n USART1_IRQHandler: %d\r\n", uart1_rx_cnt);
        // 更新温度阈值
        if(uart1_rx_cnt == 15) {
          // for(i=0; i<15; i++) {
          //   threshold[i] = uart1_rx_buf[i];
          // }
          THRESHOLD_X1 = uart1_rx_buf[0];
          THRESHOLD_X2 = uart1_rx_buf[1];
          THRESHOLD_X3 = uart1_rx_buf[2];
          THRESHOLD_X4 = uart1_rx_buf[3];
          THRESHOLD_Y1 = uart1_rx_buf[4];
          THRESHOLD_Y2 = uart1_rx_buf[5];
          THRESHOLD_Y3 = uart1_rx_buf[6];
          THRESHOLD_Y4 = uart1_rx_buf[7];
          THRESHOLD_Z1 = uart1_rx_buf[8];
          THRESHOLD_Z2 = uart1_rx_buf[9];
          THRESHOLD_Z3 = uart1_rx_buf[10];
          THRESHOLD_Z4 = uart1_rx_buf[11];
          THRESHOLD_W1 = uart1_rx_buf[12];
          THRESHOLD_W2 = uart1_rx_buf[13];
          THRESHOLD_W3 = uart1_rx_buf[14];
        }
    }
}

//�����жϴ���
void USART2_IRQHandler(void)
{
    u8 tem = 0;
    if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
    {
        if(rs485_rx_cnt < sizeof(rs485_rx_buf)-1)
        {   //δ��������rs485_rx_buf��������򽫽��յ������ݱ��浽����rs485_rx_buf
            rs485_rx_buf[rs485_rx_cnt++] = USART_ReceiveData(USART2);
        }
        // ���USART2�Ľ����жϱ�־��USART_FLAG_RXNE�����Ա��ܹ�������һ���ֽڵ�����
        USART_ClearFlag(USART2, USART_FLAG_RXNE);
    }
    if(USART_GetITStatus(USART2, USART_IT_IDLE ) != RESET )//空闲中断 接收到一帧数据 产生一次中断
    {
        tem = USART2->SR;	 //读取SR寄存器
        tem = USART2->DR;    //读取DR寄存器 (先读USART_SR，然后读USART_DR可以清除空闲中断标志位IDLE)
        USART1_printf(USART1, "\r\n USART2_IRQHandler: %d\r\n", rs485_rx_cnt);
        processTemperatureData();
    }
}

//�����жϴ���
void USART3_IRQHandler(void)
{
  // 处理读取到的电表数据
}

void mainLoop(void) {
  USART1_printf(USART1, "\r\n MainLoop!\r\n");
}

int main(void)
{   
  u8 tmp = 0;
  u8 i = 0;
	SystemInit(); // ����ϵͳʱ��Ϊ72M
	KeyInit();	  // �����ܽų�ʼ��
	// LED_GPIO_Config();// LED�ܽų�ʼ��
  RELAY_Config();// RELAY�ܽų�ʼ��
  CAN_Config(); // CAN初始化配置
  ADC_Config(); // ADC初始化配置
  USART1_Config(); //USART1���� 
  USART1_printf(USART1, "\r\n uart init done!\r\n");
  RS485_Config(); //RS485����
  for(i=0; i<=9; i++) {
    RS485_1_SendByte(i+1);
  }
 	while(1)
  {
    // GetKey();	//����Ƿ��а�������  
    delay_ms(2000);

    readRS485Temperature(); // 发送读取连接到485总线上的温度传感器的数据

    getStatusInfo(); // 发送获取液冷枪信息的CAN报文

    getNTCTemperature(); // 获取板子上热敏电阻测量计算的温度

    // // 温度处理逻辑
    // mainLoop();
  }
}




